<template>
	<view class="fullPage">
		<map id="map" :scale="scale" :latitude="latitude" :longitude="longitude" :markers="list" :show-location="true"
			@regionchange="dragMap" @markertap="markertap" @click="mapTap" style="width: 100vw;height: 100vh">
			<!-- tab栏切换 -->
			<!-- 	<cover-view class="tab_w flex_a">
				<block v-for="item in tabList" :key="item.status">
					<cover-view class="flex1 h80 lh80 border-r4 ft30 tac"
						:class="activeTab == item.status ? 'b-primary cf' : ''" @click="tapTab(item.status)">
						{{ item.name }}
					</cover-view>
				</block>
			</cover-view> -->

			<!-- 左侧的电池规则 -->
			<!-- <cover-view class="aside_l flex_a column" v-show="activeTab == 1 && !markerInfoShow">
				<block v-for="item in batterySpec" :key="item.status">
					<cover-view class="flex1 flex_aj h100 lh100 pw100 ft30 tac" :class="activeBattery == item.status ? 'b-primary cf' : ''" @click="chooseBattery(item.status)">
						{{ item.name }}
					</cover-view>
				</block>
			</cover-view> -->

			<!-- 右侧的功能按钮 -->
			<cover-view class="aside_r" v-show="!markerInfoShow">
				<!-- 钱包 -->
				<cover-view class="mb30 flex_aj w100 h110 bf  shadow moneyBao1"
					@click="routerLink({path: '/pages/user/wallet/index'},true)">
					<cover-image src="/static/ic_money.jpeg" mode="widthFix" style="width: 70upx;height: 70upx;">
					</cover-image>
					<cover-view class="money">钱包</cover-view>
				</cover-view>
				<!-- 地图按钮重置 -->
				<cover-view class="flex_aj w120 h120 bf border-r50p border-r50p shadow" @click="reset">
					<cover-image src="/static/ic_sx.png" mode="widthFix" style="width: 70upx;height: 70upx;">
					</cover-image>
				</cover-view>
			</cover-view>
			<!-- 	<cover-view class="aside_r" v-show="!markerInfoShow&&activeTab == 1">
				<cover-view class="mb30 flex_aj w100 h110 bf  shadow moneyBao1"
					@click="routerLink({path: '/pages/user/wallet/index'},true)">
					<cover-image src="/static/ic_money.jpeg" mode="widthFix" style="width: 70upx;height: 70upx;">
					</cover-image>
					<cover-view class="money">钱包</cover-view>
				</cover-view>
				<cover-view class="w120 h120 mb30">
					<cover-view class="flex_aj w120 h120 bf border-r50p shadow"
						@click="routerLink({path: '/pages/user/center/myBattery'},true)">
						<cover-image src="/static/dianchi.png" mode="widthFix" style="width: 66upx;height: 50upx;">
						</cover-image>
					</cover-view>
				</cover-view>
				<cover-view class="flex_aj w120 h120 bf border-r50p border-r50p shadow" @click="reset">
					<cover-image src="/static/ic_sx.png" mode="widthFix" style="width: 70upx;height: 70upx;">
					</cover-image>
				</cover-view>
			</cover-view> -->

			<!-- 底部tabBar start -->
			<cover-view class="tabBar" v-show="!markerInfoShow">
				<!-- 扫一扫 -->
				<cover-view class="tabBar_scan flex_aj column" @click="scanCode">
					<cover-image src="/static/ic_sys_2x.png" mode="widthFix" style="width: 128upx;height: 128upx;">
					</cover-image>
					<cover-view class="h50 lh50 ft24 c9">扫一扫</cover-view>
				</cover-view>

				<cover-view class="tabBar_c flex_sb">
					<cover-view class="flex_a">
						<cover-view class="tabBar_item flex_aj column">
							<cover-image src="/static/ic_home_02.png" mode="widthFix"
								style="width: 40upx;height: 44upx;"></cover-image>
							<cover-view class="h50 lh50 ft24 c9">首页</cover-view>
						</cover-view>
						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/user/myOrder/index' }, true)">
							<cover-image src="/static/ic_jxz.png" mode="widthFix" style="width: 44upx;height: 44upx;">
							</cover-image>
							<cover-view class="h50 lh50 ft24 c9" style="width: 100upx">充电记录</cover-view>
						</cover-view>
					</cover-view>

					<cover-view class="flex_a">

						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/user/kefu/index' })">
							<cover-image src="/static/ic_kf.png" mode="widthFix" style="width: 40upx;height: 44upx;">
							</cover-image>
							<cover-view class="h50 lh50 ft24 c9">客服</cover-view>
						</cover-view>
						<cover-view class="tabBar_item flex_aj column"
							@click="routerLink({ path: '/pages/main/mine' })">
							<cover-image src="/static/ic_center.png" mode="widthFix"
								style="width: 40upx;height: 44upx;"></cover-image>
							<cover-view class="h50 lh50 ft24 c9">我的</cover-view>
						</cover-view>
					</cover-view>
				</cover-view>
			</cover-view>
			<!-- 底部tabBar end -->

			<!-- 设备详情 start -->
			<cover-view class="map_c p30 bf border-r1 shadow" v-show="markerInfoShow">
				<!-- 充电 start -->
				<cover-view v-show="markerInfo.deviceType == 3">
					<cover-view>充电柜编号：{{ markerInfo.deviceNo }}</cover-view>
					<cover-view class="h70 flex_a">
						<cover-view class="flex1 pr24">{{ markerInfo.siteName }}</cover-view>
						<cover-view class="whn c9">{{ markerInfo.distance }}km</cover-view>
					</cover-view>
					<!-- <cover-view class="h50">{{ markerInfo.operatorName }}</cover-view> -->
					<cover-view class="flex mb20 c9 lh40">
						<cover-view class="flex_a w40 h30">
							<cover-image src="/static/ic_dw_2x.png" mode="widthFix" style="width: 24upx;height: 30upx;">
							</cover-image>
						</cover-view>
						<cover-view class="flex1">{{ markerInfo.address }}</cover-view>
					</cover-view>
					<cover-view class="flex_sb h100 mb30 plr30 bgf5">
						<cover-view class="flex_a">
							空闲仓位：
							<cover-view class="green">{{ markerInfo.blankNum }}</cover-view>
						</cover-view>
						<cover-view class="flex_a">
							总仓位：
							<cover-view class="ft30">{{ markerInfo.chanelNum }}</cover-view>
						</cover-view>
					</cover-view>
					<!-- 套餐类型  1 :按时间收费 （每小时/元） 2：按功率收费 （每度电/元） -->
					<cover-view class="h100 lh100 mb30 plr30 bgf5">
						收费标准：
						<cover-view class="inlineB pl10 danger">
							{{ markerInfo.mealPrice }}元/{{ markerInfo.mealType == 1 ? '度' : '小时' }}
						</cover-view>
					</cover-view>

					<cover-view class="h80 lh80 border-r6 b-primary tac cf tap" @click="navigation">立即导航</cover-view>
				</cover-view>
				<!-- 充电 end -->
			</cover-view>
			<!-- 设备详情 end -->
		</map>
	</view>
</template>

<script>
	import * as markersMock from '@/utils/markers.js'
	import {
		mapMutations,
		mapState
	} from 'vuex'

	import {
		getService,
		mapList,
		getDeviceDetail
	} from '@/api/user.js'
	import {
		getGiveInfo
	} from '@/api/public.js'
	export default {
		name: 'index',
		data() {
			return {
				isShowRedBag: false, // 是否显示新人红包
				getGiveInfoCode: '', //新人红包状态码
				getGiveInfoList: {}, //接收新人红包数组
				deviceNo: '',
				deviceType: 0,
				appId: '', //声明小程序的appid为空
				titless: '',
				activeTab: 3, // 1:换电柜 2：租车 3：充电柜
				tabList: [], // 头部tab栏
				activeBattery: 1, // 当前选中的电池型号
				batterySpec: [{
					name: 'DC48V',
					status: 1
				}, {
					name: 'DC60V',
					status: 2
				}, {
					name: 'DV72V',
					status: 3
				}], // 电池型号列表
				scale: 14, // 地图缩放比例
				latitude: 23.12652, //23.02067
				longitude: 113.25878, //113.75179  
				list: [], // 设备列表
				markerInfoShow: false, // 是否显示marker点详情
				markerInfo: {}, // marker点相亲
				isShowBat: false, // 是否显示电池详情
				isTapScan: false, // 是否可以正常扫码 （阻止用户同一时间点，多次点击）

			}
		},
		onLoad(e) {
			this.appId = uni.getAccountInfoSync().miniProgram.appId //获取小程序的appid
			this.mapContext = uni.createMapContext('map')
			this.init()
			// 让分享与分布朋友圈按钮能用
			uni.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})

		},
		// 转发功能样式定制
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}

			return {
				title: '智能充电柜', //分享的名称
				path: '/pages/main/map',
				mpId: this.appId //此处配置微信小程序的AppId
			}
		},
		//分享到朋友圈
		onShareTimeline(res) {
			return {
				title: '智能充电柜',
				type: 0,
				summary: "",
			}
		},

		onShow() {
			setTimeout(() => {
				console.log('0000000000', this.longitude, this.latitude);
				this.$store.commit('longitudess', this.longitude)
				this.$store.commit('latitudess', this.latitude)
			}, 1000)
			setTimeout(() => {
				this.$store.commit('longitudess', this.longitude)
				this.$store.commit('latitudess', this.latitude)
			}, 5000)
			setTimeout(() => {
				this.$store.commit('longitudess', this.longitude)
				this.$store.commit('latitudess', this.latitude)
			}, 10000)
			setTimeout(() => {
				this.$store.commit('longitudess', this.longitude)
				this.$store.commit('latitudess', this.latitude)
			}, 20000)
			setTimeout(() => {
				this.$store.commit('longitudess', this.longitude)
				this.$store.commit('latitudess', this.latitude)
			}, 50000)
		},
		onHide() {
			this.macno = null
		},
		computed: {
			isLogin() {
				return this.$store.state.user.isLogin
			},
			...mapState({
				tabbarstatus: state => state.tabbar.tabbarstatus,
				deviceTypes: state => state.tabbar.deviceTypes,
			})
		},

		methods: {
			async init() {
				// await this.getService()
				this.getLocation()
			},
			// 获取后端返回的数据，判断当前是充电桩或换电柜或租车
			async getService() {
				//调用接口，并用小程序的appid传参
				const res = await getService({
					appId: this.appId
				})
				// console.log('getService--res---', res);
				const service = res.data
				const _tabList = []
				// 运营充电  1：是 2：否
				if (service.operateCd == 1) {
					_tabList.push({
						name: '充电',
						status: 3
					})
				}
				// 运营换电  1：是 2：否
				if (service.operateHd == 1) {
					_tabList.push({
						name: '换电',
						status: 1
					})
				}
				//此时_tabList的样式是这样：_tabList[{name:xxx,status:xxx}]
				// console.log('_tabList==', _tabList);
				this.tabList = _tabList
				this.activeTab = _tabList[0] ? _tabList[0].status : 0
			},
			// 点击tab栏
			tapTab(status) {
				if (this.activeTab == status) {
					return false
				}
				this.markerInfoShow = false
				this.activeTab = status
				this.getList()
				this.$store.commit('tapTab', status)
			},

			//获取当前的地理位置(经纬度)
			async getLocation() {

				let [a, {
					latitude,
					longitude
				}] = await uni.getLocation({
					type: 'gcj02', //默认值  工具中定位模拟使用 IP 定位，可能会有一定误差。且工具目前仅支持 gcj02 坐标。
				})
				console.log('================================', latitude, longitude);
				this.latitude = latitude
				this.longitude = longitude

				this.getList()
			},

			getList() {
				// console.log("this.list-----", this.list)
				//移除 marker
				this.mapContext.removeMarkers({
					markerIds: this.list.map(item => item.id)
				})

				this.list = []
				//将地图中心移置当前定位点，此时需设置地图组件 show-location 为true。2.8.0 起支持将地图中心移动到指定位置
				this.mapContext.moveToLocation({
					longitude: this.longitude,
					latitude: this.latitude
				})
				this.list[0] = {
					id: -1,
					latitude: this.latitude * 1,
					longitude: this.longitude * 1,
					iconPath: '/static/ic_dqdw_2x.png',
					width: 100,
					height: 100
				}
				// if (this.tabList.length > 0) {
				this.mapList()
				// }
				// this.markersMock()
			},


			// 模拟数据
			markersMock() {
				console.log('markersMock');
				let markers = []
				markersMock.markers.forEach((item, index) => {
					markers.push({
						id: index,
						latitude: item.lat,
						longitude: item.lng,
						width: 42,
						height: 44,
						iconPath: '/static/ic_pos.png',
						title: '',
						anchor: {
							x: 0.5,
							y: 0.5
						}
					})
				})
				this.list = [...this.list, ...markers]
			},
			// 附近设备
			async mapList() {

				const res = await mapList({
					serviceType: this.activeTab,
					lat: this.latitude,
					lng: this.longitude,
					appId: this.appId
				})
				console.log("mapList-----", res)
				this.list = []
				res.data.forEach((item, index) => {
					const localInfo = {
						index: index,
						id: index,
						deviceId: item.id,

						// title: item.name,
						// macno: item.macno,
						// address: item.address,
						// distance: item.distance,
						// is_enable: item.is_enable,

						latitude: item.lat * 1,
						longitude: item.lng * 1,
						width: 70,
						height: 70,
						iconPath: '/static/ic_sbdw_2x.png',
						anchor: {
							x: 0.5,
							y: 0.5
						}
					}
					this.list.push(localInfo)
				})
				// this.markerInfo = this.list[1]
			},

			// 获取设备详情
			async getDeviceDetail(index) {

				const res = await getDeviceDetail({
					serviceType: this.activeTab,
					lat: this.latitude,
					lng: this.longitude,
					id: this.list[index].deviceId !== undefined ? this.list[index].deviceId : ""
				})
				this.markerInfoShow = true
				res.data.index = index
				this.markerInfo = res.data
				console.log(222222222, this.list[index + 1].deviceId);
				console.log(77777777777777777, this.markerInfo)
			},

			markertap(e) {
				console.log(e, 77777777777777777)
				console.log(this.list)
				if (e.detail.markerId < 0) {
					return false
				}

				if (this.markerInfo.id == this.list[e.detail.markerId].deviceId) {
					this.markerInfoShow = true
					return false
				}

				this.getDeviceDetail(e.detail.markerId)
			},
			dragMap(e) {
				// 注意：支付宝小程序 如果缩小或者放大了地图比例尺以后，请在 onRegionChange 函数中重新设置 data 的
				// scale 值，否则会出现拖动地图区域后，重新加载导致地图比例尺又变回缩放前的大小。
				// #ifdef MP-ALIPAY
				console.log('1=1================', e)
				console.log(e.scale)
				this.scale = e.scale
				// 获取当前地图中心的经纬度
				this.mapContext.getCenterLocation({
					success: res => {
						console.log(res.longitude)
						console.log(res.latitude)

						this.latitude = res.latitude
						this.longitude = res.longitude
					},
					fail: err => {
						console.log(err)
					}
				})
				// #endif
				console.log('地图被拖动')
				this.markerInfoShow = false
			},
			mapTap() {
				console.log('地图被点击')
				// this.markerInfoShow = false
			},
			// 地图按钮方法
			async reset() {
				console.log('点击地图定位按钮===========', this.latitude);

				this.scale = 14
				this.mapContext.moveToLocation({
					latitude: this.latitude,
					longitude: this.longitude
				})
				this.getLocation()
			},

			// 扫一扫
			scanCode() {
				console.log('我扫码进来了===========');
				// 防抖
				if (this.isTapScan) {
					return false
				}
				this.isTapScan = true
				setTimeout(() => {
					this.isTapScan = false
				}, 2000)


				const _self = this
				this.routerLink({}, true, () => {
					uni.scanCode({
						scanType: ['barCode', 'qrCode'], //扫码类型
						success(res) {
							if (res.errMsg == 'scanCode:ok') {
								console.log(' 这是我需要的', res);
								let deviceNo = ''
								let deviceType = 0
								if (res.scanType == 'QR_CODE') { //扫的码是二维码类型
									// 获取路由url的参数值
									deviceNo = _self.getUrlParam('deviceNo', res.result)
									deviceType = _self.getUrlParam('deviceType', res.result)
									_self.$store.commit('scanCode', deviceType)
									_self.deviceNo = deviceNo
									_self.deviceType = deviceType
									console.log(_self.deviceTypes, _self.deviceNo);

								}
								if (deviceNo) {
									console.log('=========', deviceNo);
									// _self.getGiveInfo(deviceNo) // 调用// 获取新人红包  方法

									setTimeout(() => {
										if (_self.getGiveInfoCode == 'FAIL') {
											_self.goUsePage(deviceNo,
												deviceType) //// 调用 -- 跳转 设备使用页面  
										} else {
											_self.isShowRedBag = true
											// setTimeout(() => {
											// 	_self.isShowRedBag = false
											_self.goUsePage(deviceNo,
												deviceType) //// 调用 -- 跳转 设备使用页面  
											// }, 3000)
										}
									}, 1000)


								} else {
									_self.toast('请扫描正确的二维码')
								}
							}
						},


						fail(err) {
							console.log(err)
						}
					})
				})


			},
			// 获取新人红包  
			async getGiveInfo(deviceNo) {
				const res = await getGiveInfo({
					deviceNo: deviceNo
				})
				this.getGiveInfoCode = res.msg
				this.getGiveInfoList = res.data

			},
			// 跳转 我的钱包
			goWallet() {
				uni.redirectTo({
					url: '/pages/user/wallet/index'
				})
			},
			// 跳转 设备使用页面
			goUsePage(deviceNo, deviceType) {
				// deviceType设备类型 1:换电柜 2：租车 3：充电柜
				let page = ''
				let query = {
					deviceNo,
					lat: this.latitude,
					lng: this.longitude
				}
				page = '/pages/user/chargeEle/index'
				this.routerLink({
					path: page,
					query
				})
			},

			navigation() {

				uni.openLocation({
					latitude: this.markerInfo.lat * 1,
					longitude: this.markerInfo.lng * 1,
					name: this.markerInfo.siteName,
					address: this.markerInfo.address,
					success: () => {
						this.markerInfoShow = false
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.inlineB {
		display: inline-block;
		vertical-align: middle;
		white-space: nowrap;
	}

	cover-view {
		overflow: auto;
		white-space: normal;
	}

	.tab_w {
		position: fixed;
		top: 30upx;
		left: 26upx;
		width: 698upx;
		height: 100upx;
		padding: 10upx 14upx;
		box-sizing: border-box;
		background-color: #fff;
		border-radius: 50upx;
		overflow: hidden;
		box-shadow: 0px 4px 18px 0px rgba(50, 130, 255, 0.24);
	}

	.aside_l {
		position: fixed;
		bottom: 330upx;
		left: 26upx;
		width: 160upx;
		height: 300upx;
		background: #ffffff;
		box-shadow: 0upx 4upx 18upx 0upx rgba(50, 130, 255, 0.24);
		border-radius: 20upx;
		overflow: hidden;
	}

	.aside_r {
		position: fixed;
		bottom: 360upx;
		right: 26upx;
	}

	// 底部tabbar
	.tabBar {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 210upx;

		.tabBar_scan {
			position: absolute;
			top: 0;
			left: 50%;
			z-index: 2;
			transform: translateX(-50%);
		}

		.tabBar_c {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 150upx;
			padding: 20upx;
			box-sizing: border-box;
			background: #ffffff;
			box-shadow: 1upx -14upx 20upx 0upx rgba(50, 130, 255, 0.1);
			border-radius: 50upx 50upx 0upx 0upx;

			.tabBar_item {
				// flex: 1;
				width: 140upx;
			}
		}
	}

	.map_c {
		position: fixed;
		bottom: 60upx;
		left: 30upx;
		width: 690upx;
		box-sizing: border-box;
	}

	.bat_wrap {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba($color: #000000, $alpha: 0.4);

		.bat_content {
			width: 600upx;
			min-height: 462upx;
			padding: 40upx 30upx;
			margin-bottom: 30upx;
			background-color: #fff;
			border-radius: 10px;

			.table_th {
				height: 50upx;
				line-height: 50upx;
				background: #deeafd;
			}

			.table_tr {
				height: 60upx;
				line-height: 60upx;
				background: #f7faff;
			}
		}

		.bat_close {
			width: 60upx;
			height: 60upx;

			&:active {
				opacity: 0.8;
			}
		}
	}

	.hongbao {
		// z-index: 1000;
		position: absolute;
		top: 20%;
		bottom: 20%;
		left: 10px;

		.cp_w {
			position: relative;
			width: 654upx;
			height: 876upx;

			.cp_img {
				position: absolute;
				left: 0;
				top: 0;
				z-index: 0;
			}

			.cp_c {
				position: relative;
				z-index: 1;
				padding-top: 370upx;

				.cp_money {

					font-family: Source Han Sans CN;
					font-weight: bold;
					color: #ffffff;
					// line-height: 206px;
					// text-shadow: 0px 4px 0px rgba(167, 7, 46, 0.45);
					background: linear-gradient(180deg, #fffdc9 0%, #ffdb6d 100%);
					-webkit-background-clip: text;
					-webkit-text-fill-color: transparent;
				}

				.cp_close {
					background-color: red;
					width: 25px;
					height: 25px;
					line-height: 23px;
				}
			}
		}
	}

	.moneyBao1 {
		flex-direction: column;
		border-radius: 50%;
		// position: relative;
		padding: 4px;

		.money {
			position: relative;
			font-size: 12px;
		}

	}
</style>